package com.generator.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

public class DBUtil {

    /**
     * 把SQL语句查询出列表
     *
     * @param sql
     * @param conn
     * @return
     */
    public static List getDataBySQL(String sql, Connection conn) {
        Statement stmt = null;
        ResultSet rs = null;
        List list = new ArrayList();
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String[] arr = new String[rs.getMetaData().getColumnCount()];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = rs.getString(i + 1);
                }
                list.add(arr);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection(String url,String username,String password) {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

//    private static  String  dbName = "tool_plat";
//    private static String tableName = "sys_user";
//    private static String url = "jdbc:mysql://127.0.0.1:3306/";
//    private static String account = "root";
//    private static String password = "root";

//    public static void test(){
//        String allColumn = "select column_name,data_type,character_octet_length,COLUMN_COMMENT,is_nullable,COLUMN_key from information_schema.`COLUMNS` where TABLE_NAME='"+tableName+"' and TABLE_SCHEMA='" + dbName + "'";
//        Connection conn = getConnection(url,account,password);
//        List columns = getDataBySQL(allColumn, conn);
//        for (Iterator iterator = columns.iterator(); iterator.hasNext(); ) {
//            String[] col = (String[]) iterator.next();
//            System.out.println(col[0]+ "  " + col[1]);
//        }
//    }
}
